﻿using System;
using System.Linq;
using System.Collections.ObjectModel;

namespace Transportr
{
    public class BrowserModel : Model
    {
        public const int MAX_ITEM = 50;
        public Metadata.LineFilter Filter { get; set; } // TODO

        public ObservableCollection<LineItemViewModel> Items { get; private set; }

        public ObservableCollection<LineItemViewModel> FilteredItems
        {
            get
            {
                ObservableCollection<LineItemViewModel> ret = new ObservableCollection<LineItemViewModel>();
                foreach(LineItemViewModel i in Items)
                {
                    if (ret.Count < MAX_ITEM && i.LineNumber.Contains(Filter.Text))
                        ret.Add(i);
                }
                return ret;
            }
        }

        public event UpdatedHandler Updated;

        public bool IsDataLoaded { get; private set; }

        public BrowserModel()
        {
            this.Filter = new Metadata.LineFilter();
            this.Items = new ObservableCollection<LineItemViewModel>();
        }

        public void BeginUpdate()
        {
            IsDataLoaded = false;
            Service.SendRequest(ServiceModel.Function.Lines, new ServiceModel.Parameters(), EndUpdate, false);
        }

        void EndUpdate(object sender, Service.RequestState state) {
#if WINDOWS_PHONE
            System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => {
#endif
                    foreach (ServiceModel.Line l in state.Response.Lines.Line)
                    {
                            this.Items.Add(new LineItemViewModel()
                            {
                                lnId = l.lnId,
                                mltId = l.ltId,
                                LineNumber = l.lnNumber,
                                Route = String.Format("{0} - {1}", l.endName1, l.endName2),
                                LineType = Icon.Vehicle((ServiceModel.VehicleType)l.ltId)
                            });
                    }

                    if (Updated != null)
                        if (this.Items.Count > 0) Updated("");
                        else Updated("No items to display");
                    this.IsDataLoaded = true;
#if WINDOWS_PHONE
                });
#endif
        }
    }
}
